<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <el-tabs @tabChange="tabChange" v-model="form.platform_id" class="w-full" @tab-change="query">
          <el-tab-pane v-for="(d, index) in options.platform" :key="index" :name="d.value" :label="d.label"></el-tab-pane>
        </el-tabs>
        <VSelect v-model="form.platform_id" placeholder="平台" :options="options.platform" multiple collapse-tags
          style="min-width: 160px" />
        <VSelect v-model="form.type" placeholder="错误类型" :options="options.type" multiple collapse-tags
          style="min-width: 160px" />
        <VSelect v-model="form.statuses" placeholder="状态" :options="options.status" multiple collapse-tags
          style="min-width: 160px" />
        <VCascader v-model="form.create_id" placeholder="创建人" multiple collapse-tags style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 100px">
            <el-option label="创建时间" value="create_time"></el-option>
          </el-select>
          <el-date-picker v-model="form.dateRange.value" type="daterange" value-format="YYYY-MM-DD" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" style="max-width: 260px" />
        </VGroup>
        <VGroup>
          <el-select v-model="form.input.type" style="width: 100px">
            <el-option label="错误代码" value="error_code"></el-option>
            <el-option label="中文说明" value="cn_explain"></el-option>
            <el-option label="英文说明" value="en_explain"></el-option>
            <el-option label="关键词" value="keyword"></el-option>
          </el-select>
          <el-input v-model="form.input.value" placeholder="请输入" class="w-60" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VButton :auth="authMatched?.edit" type="primary" icon="DocumentAdd" @click="create(tableRef)">添加</VButton>
        <VButton :auth="authMatched?.enable" :loading="loadings.enable2" @click="handleBatch('enable2')">启用</VButton>
        <VButton :auth="authMatched?.enable" :loading="loadings.enable1" @click="handleBatch('enable1')">禁用</VButton>
        <VButton :auth="authMatched?.enable" :loading="loadings.delete" @click="handleBatch('delete')">删除</VButton>
        <VImport :tableRef="tableRef" importUrl="/v1/material/upc/import"
          downloadUrl="https://xc-base.oss-cn-shenzhen.aliyuncs.com/template/listing_error.xlsx" class="ml-auto" />
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
  </VPage>
</template>
  
<script setup lang="jsx" name="Account">
import api from './api'
import Add from './components/Add'
import VImport from '@/components/VImport'
import { getOption } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'
import {computed} from "vue";

const authMatchPlatform = {
  // eBay
  1: {
    add: '/base/error/ebay/add', // 添加
    enable: '/base/error/ebay/enable', // 启用禁用删除,
    edit: '/base/error/ebay/update', // 编辑
  },
  // Amazon
  2: {
    add: '/base/error/amazon/add', // 添加
    enable: '/base/error/amazon/enable', // 启用禁用删除,
    edit: '/base/error/amazon/update', // 编辑
  },
  // OTTO
  3: {
    add: '/base/error/otto/add', // 添加
    enable: '/base/error/otto/enable', // 启用禁用删除,
    edit: '/base/error/otto/update', // 编辑
  },
  // Walmart
  4: {
    add: '/base/error/walmart/add', // 添加
    enable: '/base/error/walmart/enable', // 启用禁用删除,
    edit: '/base/error/walmart/update', // 编辑
  },
  // 其他平台
  5: {
    add: '/base/error/other/add', // 添加
    enable: '/base/error/other/enable', // 启用禁用删除,
    edit: '/base/error/other/update', // 编辑
  },
}

const baseName = 'listing_error'
const tableRef = ref()
const currentTab = ref(1)
const loadings = reactive({})
const authMatched = computed(() => {
  return authMatchPlatform[currentTab.value] || {}
})
// 查询
const query = () => {
  tableRef?.value.query()
}

const tabChange = v => {
  currentTab.value = v
}

// 新增
const addRef = ref()
const create = () => {
  addRef?.value.open()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 批量操作
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const le_ids = selection.map(d => d.le_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    used: () => {
      showLoading()
      api.used({ le_ids, used: 2 }).then(res => {
        ElMessage({ type: 'success', message: '操作成功', })
        query()
      }).finally(closeLoading)
    },
    enable2: () => {
      showLoading()
      api.enable({ le_ids, status: 2 }).then(res => {
        ElMessage({ type: 'success', message: '操作成功', })
        query()
      }).finally(closeLoading)
    },
    enable1: () => {
      showLoading()
      api.enable({ le_ids, status: 1 }).then(res => {
        ElMessage({ type: 'success', message: '操作成功', })
        query()
      }).finally(closeLoading)
    },
    delete: () => {
      ElMessageBox.confirm('是否确认删除？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.delete({ le_ids }).then(res => {
            ElMessage({ type: 'success', message: '操作成功', })
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
  }
  handle[name]()
}
// 单行操作
const handleRow = (name, row, rowIndex) => {
  const { le_id } = row
  num.value = Math.random()
  const showLoading = (name = 'handle') => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = (name = 'handle') => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    edit: () => {
      addRef?.value.open(le_id)
    },
    delete: () => {
      ElMessageBox.confirm('是否确认删除？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.delete({ le_ids: [le_id] }).then(res => {
            ElMessage({ type: 'success', message: '操作成功', })
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    }
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  showHeaderOverflow: false,
  formConfig: {
    data: {
      platform_id: 1,
      input: { type: 'error_code', value: '' }, // 组合
      dateRange: { type: 'create_time', value: [], range: true }, // 组合
    }
  },
  columns: [
    { type: 'checkbox', fixed: 'left', width: 40 },
    { title: '信息编号', field: 'le_id', minWidth: 100 },
    { title: '平台', field: 'platform_name', minWidth: 100 },
    { title: '错误代码', field: 'error_code', minWidth: 100 },
    { title: '错误类型', field: 'type_name', minWidth: 100 },
    { title: '关键词', field: 'keyword', minWidth: 100 },
    {
      title: '英文说明', field: 'en_explain', minWidth: 140, line: 2
    },
    {
      title: '中文说明', field: 'cn_explain', minWidth: 140, line: 2
    },
    {
      title: '解决方案', field: 'solution', minWidth: 140, line: 2
    },
    { title: '创建人', field: 'create_name', minWidth: 120 },
    { title: '创建时间', field: 'create_time', minWidth: 170 },
    {
      title: '状态', field: 'status', minWidth: 100, slots: {
        default: ({row}) => <VStatus status={row.status === 2} />
      }
    },
    {
      title: '备注', field: 'remark', minWidth: 120, line: 2
    },
    {
      title: '操作', width: 110, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          return <div>
            <VButton auth={authMatched.value.edit} link type="primary" onClick={() => handleRow('edit', row)}>编辑</VButton>
            <VButton auth={authMatched.value.enable} link type="danger" onClick={() => handleRow('delete', row, rowIndex)}>删除</VButton>
          </div>
        }
      }
    }
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page })
    }
  }
})
</script>
  